import axios from 'axios'
// 直接引入路由实例和vuex实例
// 因为组件是一个vue实例，所以它有$router和$store
import Vue from 'vue'
const vm = new Vue()

// 通用数据配置
const Axios = axios.create({
    timeout: 25000,
    baseURL: '/hongchuang'
})

// axios有拦截器
const other = ['/user/login', '/user/validate/code', '/user/app/login']
const requestHook = function(config) {
    if (other.includes(config.url)) return config
    let token = vm.$myStore.getters['common/token']
    if (!token) return Promise.reject({code: 400, message: '没有token数据，不可以发出请求'})
    config.headers.token = token
    return config
}
// 实现请求拦截
Axios.interceptors.request.use(requestHook)

// 实现响应拦截
Axios.interceptors.response.use(function(response) {
    let { data } = response
    // 判断data的code是否是403，message是否为："Request information authentication failed."
    if (data.code === 403 && data.message === "Request information authentication failed.") {
        alert('用户登录失效，请重新登录')
        vm.$myRouter.push('/login')
    } else {
        return response
    }
})

// 基于Promise
/**
 * 封装的axios异步请求方法
 * @param {{url: string, method: 'get' | 'post' | 'delete' | 'put', data: any, params: any}} req 请求对象
 * @return Promise
 */
export default req => {
    if (!req || !req.url) throw new TypeError('url地址必传')
    return new Promise(resolve => {
        Axios({
            url: req.url,
            // 默认为post
            method: req.method || 'get',
            params: req.params || {},
            data: req.data || {}
        }).then( ({data}) => {
            resolve(data)
        }).catch( ({code, message}) => {
            resolve({code, message})
        })
    })
}